//
// Session test
//
// >curl -c c -b c "http://localhost:3004/logout"
// "OK"
// >curl -c c -b c "http://localhost:3004/login?uname=jani"
// {"sid":107,"data":{"uname":"jani"}}
// >curl -c c -b c "http://localhost:3004/ses"
// {"sid":"107","data":{"uname":"jani"}}
// >curl -c c -b c "http://localhost:3004/logout"
// "OK"
// >curl -c c -b c "http://localhost:3004/ses"
// {"sid":108,"data":{}}
//

var JServer = require( '../jserver' );
var Session = require( '../session' );
var SessionStore = require( '../session-redis' );
var server = new JServer( {workers:1} );
server.ServerResponse.allowOrigin = '*';
if ( server.start() ) return;

var ses = new Session( {key:'jsid',secret:'b6f90Fad85FC07', verbose:true}, new SessionStore() );

server.get( "/ses", function(req,res) {
	ses.start( req, res, function(err) {
		var o = "Request headers:\n";
		for (var k in req.headers)
			o += k+": "+req.headers[k]+"\n";
		console.log( o );
		
		res.json( err ? err : {sid:req.sid,data:req.session} );
	} );
} );

server.get( "/login", function(req,res) {
	ses.start( req, res, function(err) {
		if (err) return res.json( err );
		console.log( "sid="+req.sid );
		req.session.uname = (req.query.uname ? req.query.uname : 'guest');
		ses.save( req, res, function(err) {
			console.log( err ? err : "saved session.uname="+req.session.uname );
			res.json( err ? err : {sid:req.sid,data:req.session} );
		} );
	} );
} );

server.get( "/logout", function(req,res) {
	ses.destroy( req, res, function(err) {
		res.json( err ? err : "OK" );
	} );
} );

server.listenHTTP( 3004 );
